package com.gitee.somenvm.ninerpgitem.core.item

import com.gitee.somenvm.ninerpgitem.api.event.item.NineItemDataInitEvent
import com.gitee.somenvm.ninerpgitem.api.item.NineItem
import com.gitee.somenvm.ninerpgitem.api.item.NineItemOption
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import taboolib.library.configuration.ConfigurationSection
import taboolib.library.xseries.XItemStack
import taboolib.module.configuration.util.getMap
import taboolib.module.kether.KetherShell
import taboolib.module.kether.ScriptOptions
import taboolib.module.nms.ItemTag
import taboolib.module.nms.ItemTagData
import taboolib.module.nms.getItemTag


/// 配置物品
class NineItem(override val root: ConfigurationSection) : NineItem {

    override val id: String = root.name
    override var name: String = root.getString("name", "?")!!

    class Option(itemStack: ItemStack? = null) : NineItemOption {
        override var action: Map<String, String> = hashMapOf()

        init {
            itemStack?.let { item ->
                ItemLoader[item.getID()]?.root?.getMap<String, String>("action")
            }
        }

        override fun clone(): NineItemOption {
            return Option().also {
                it.action = this.action
            }
        }
    }

    fun build(player: Player): ItemStack {
        return build(player, Option()) {}
    }

    override fun build(player: Player, option: NineItemOption, func: (ItemStack) -> Unit): ItemStack {
        val item = XItemStack.deserialize(root.getConfigurationSection("display")!!)
        val nbt: ItemTag = item.getItemTag().also {
            it += ItemTagData.toNBT(root.getConfigurationSection("nbt")).asCompound()
            it["NRI.ID"] = ItemTagData.toNBT(id)
        }
        nbt.saveTo(item)

        val data = item.getNineData(this, player)

        item.getItemTag().also {
            it.putDeep("NRI.ID", id)
        }.saveTo(item)

        item.update(data, this@NineItem, player, func)
        return item
    }

    //初始化Data数据
    fun initData(scriptOptions: ScriptOptions): NineData {
        val data = NineData()
        val dataCs = root.getConfigurationSection("data")
        dataCs?.getKeys(true)?.forEach { key ->
            val value = dataCs[key]
            data[key] = when (value) {
                is String -> KetherShell.eval(value, scriptOptions).thenApply { it }
                else -> value
            }
        }
        NineItemDataInitEvent(data).call()
        scriptOptions.vars.map["@data"] = data
        return data

    }

    override fun toString(): String {
        return "NineItem(id='$id', name='$name')"
    }
}